package com.situ.springboot.controller;

import com.situ.springboot.pojo.vo.CountCustomidVo;
import com.situ.springboot.pojo.vo.CountServiceidVo;
import com.situ.springboot.service.RecordService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ExcelController {

    @Autowired
    private RecordService recordService;//获取两张报表

    //导出用户报表
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response) throws Exception {
        // 创建Excel文档
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Sheet1");
        XSSFSheet sheet2 = workbook.createSheet("Sheet2");

        // 创建表头
        XSSFRow header = sheet.createRow(0);
        header.createCell(0).setCellValue("用户Id");
        header.createCell(1).setCellValue("用户名称");
        header.createCell(2).setCellValue("消费次数");



        // 创建表头2
        XSSFRow header2 = sheet2.createRow(0);
        header2.createCell(0).setCellValue("服务Id");
        header2.createCell(1).setCellValue("服务项目");
        header2.createCell(2).setCellValue("选择人数");




        // 填充数据
        List<CountCustomidVo> customidVos = recordService.selectByCustomIdCount();
        int rowIndex = 1;
        for (CountCustomidVo countCustomidVo : customidVos) {
            XSSFRow row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(countCustomidVo.getId());
            row.createCell(1).setCellValue(countCustomidVo.getName());
            row.createCell(2).setCellValue(countCustomidVo.getNumber());
        }

        // 填充数据2
        List<CountServiceidVo> serviceidVos = recordService.selectByServiceIdCount();
        int rowIndex2 = 1;
        for (CountServiceidVo countServiceidVo : serviceidVos) {
            XSSFRow row = sheet2.createRow(rowIndex2++);
            row.createCell(0).setCellValue(countServiceidVo.getId());
            row.createCell(1).setCellValue(countServiceidVo.getName());
            row.createCell(2).setCellValue(countServiceidVo.getNumber());
        }

        // 设置响应头信息
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=users.xlsx");

        // 将Excel文档写入响应流中
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
